using UnityEngine;
using System.Collections;
using System.Collections.Generic;

//挂在相机上
//把相机的scale设置成-1，
//半透明叠加
//1.设置可反射物体
// 2
/**不可反射设置到NonRefractable
*/
public class PlanarReflection :MonoBehaviour{

    private Camera reflectCam;

    public Vector3 T = Vector3.zero;
    public Vector3 R = Vector3.zero;
    public Vector3 S = Vector3.one;

    private RenderTexture reflectRT;

    void Start()
    {
        //游戏启动后会在场景自动加一个ReflectCam
       GameObject go= new GameObject("Reflection",new []{typeof(Camera)});
       reflectCam = go.GetComponents<Camera>();
       reflectCam.CopyFrom(Camera.main);
    
    //不用深度信息
       reflectRT = RenderTexture.GetTemporary(Screen.width,Screen.height,0);// 创建一个临时的渲染纹理
      reflectRT.name = "ReflectRT";
      reflectRT.SetGlobalShaderProperty("_ReflectRT");//设置全局的shader属性

       RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
    }	
    private void OnBeginCameraRendering(ScriptableRenderContext ctx,Camera cam)
    {
       if(cam == reflectCam)
       {

        reflectCam.CopyFrom(Camera.main);
        reflectCam.clearFlags = CameraClearFlags.SolidColor;
        reflectCam.backgroundColor = Color.clear;//背景不渲染，和主相机融合
        reflectCam.targetTexture = reflectRT;
        // reflectCam.Render();
        //编辑器中设置好不可反射物体
       cam.cullingMask = LayerMask.GetMask("NonRefractable");//只渲染NonRefractable
        
        // Debug.LogError(cam);
        // cam.worldToCameraMatrix = GetReflectMatrix(cam.worldToCameraMatrix);
      //GL是unity的内部，
        GL.invertCulling = true;//渲染师物体表面背面，所以要开启反向剔除，（默认正向剔除背面三角形）
        cam.worldToCameraMatrix = Camera.main.worldToCameraMatrix * Matrix4x4.TRS(T,Quaternion.Euler(R),S);
        //欧拉角转四元数 
       }

       else
       {
        GL.invertCulling = false;//主摄像机正常渲染时候，还原到正向剔除状态
       }
    }
    void Update()
    {
        Shader.globalMaximumLOD = (int)graphicLevel;//转成整数
    }
}
